package handlers

import (
	"fmt"
	"net/http"
	"runtime"
	"strings"

	"github.com/coreos/go-iptables/iptables"
	"github.com/gin-gonic/gin"
)

func GetIPHandler(c *gin.Context) {
	// 获取开放 5060 端口的 IP 列表
	ipList, err := getIPTablesInput5060()
	if err != nil {
		c.JSON(http.StatusOK, Response{0, "执行 iptables 命令失败", ipList})
		return
	}
	c.JSON(http.StatusOK, Response{1, "成功", ipList})
}

func AddIPHandler(c *gin.Context) {
	var req struct {
		IP string `json:"ip"`
	}
	if c.BindJSON(&req) != nil {
		c.JSON(http.StatusBadRequest, Response{0, "请求错误", nil})
		return
	}

	ipMutex.Lock()
	defer ipMutex.Unlock()
	ipList = append(ipList, map[string]interface{}{
		"id":        len(ipList) + 1,
		"ipaddress": req.IP,
	})
	c.JSON(http.StatusOK, Response{1, "添加成功", nil})
}

// 解析 iptables 输出，提取指定端口的规则
func parseIPTablesOutput(output, targetPort string) []string {
	var rules []string
	lines := strings.Split(output, "\n")

	for _, line := range lines {
		// 查找包含目标端口的规则
		if strings.Contains(line, "dpt:"+targetPort) {
			rules = append(rules, strings.TrimSpace(line))
		}
	}

	return rules
}

// 获取 iptables INPUT 链中开放 5060 端口的 IP 列表
func getIPTablesInput5060() ([]string, error) {
	if runtime.GOOS == "windows" {
		return []string{}, nil
	}

	// 初始化iptables
	ipt, err := iptables.New()
	if err != nil {
		return nil, fmt.Errorf("初始化iptables失败: %v", err)
	}

	// 获取INPUT链规则
	rules, err := ipt.List("filter", "INPUT")
	if err != nil {
		return nil, fmt.Errorf("获取iptables规则失败: %v", err)
	}

	// 解析规则，提取开放5060端口的IP地址
	ipList := parseIPTablesOutput(strings.Join(rules, "\n"), "5060")
	return ipList, nil
}
